package com.yuanqi.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yuanqi.mapper.AttachmentTypeConfigMapper;
import com.yuanqi.pojo.AttachmentTypeConfig;
import com.yuanqi.service.AttachmentTypeConfigService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.ArrayList;

/**
 * 附件类型配置服务实现类
 */
@Service
public class AttachmentTypeConfigServiceImpl extends ServiceImpl<AttachmentTypeConfigMapper, AttachmentTypeConfig> 
        implements AttachmentTypeConfigService {
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    public List<AttachmentTypeConfig> getByStatus(Integer status) {
        return baseMapper.selectByStatus(status);
    }
    
    @Override
    public AttachmentTypeConfig getByTypeCode(String typeCode) {
        return baseMapper.selectByTypeCode(typeCode);
    }
    
    @Override
    public List<AttachmentTypeConfig> getEnabledOrderBySort() {
        return baseMapper.selectEnabledOrderBySort();
    }
    
    @Override
    public boolean isFileTypeAllowed(String fileName, String typeCode) {
        AttachmentTypeConfig config = getByTypeCode(typeCode);
        if (config == null || config.getStatus() != 1) {
            return false;
        }
        
        List<String> allowedExtensions = getAllowedExtensions(typeCode);
        String extension = getFileExtension(fileName);
        return allowedExtensions.contains(extension.toLowerCase());
    }
    
    @Override
    public long getMaxFileSize(String typeCode) {
        AttachmentTypeConfig config = getByTypeCode(typeCode);
        return config != null ? config.getMaxFileSize() : 10485760L; // 默认10MB
    }
    
    @Override
    public List<String> getAllowedExtensions(String typeCode) {
        AttachmentTypeConfig config = getByTypeCode(typeCode);
        if (config == null) {
            return new ArrayList<>();
        }
        
        try {
            return objectMapper.readValue(config.getAllowedExtensions(), new TypeReference<List<String>>() {});
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
    
    private String getFileExtension(String fileName) {
        if (fileName == null || !fileName.contains(".")) {
            return "";
        }
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }
}
